package com.lagou.edu.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MyFilter implements GlobalFilter, Ordered {

    @Value("${limit.count}")
    private int limitCount;

    @Value("${limit.times}")
    private int limitTimes;

    //key为IP，value为注册的次数
    private static Map<String, Integer> registerTimesMap = new HashMap<>();
    //key为IP，value为注册最近一次的时间
    private static Map<String, Long> registerSecondsMap = new HashMap<>();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String clientIp =
                request.getRemoteAddress().getHostString();

        String path = request.getPath().toString();
        if(!path.startsWith("/api/user") && !path.startsWith("/api/code")){
            List<HttpCookie> token = request.getCookies().get("token");
            if(token == null || token.size()<=0){

                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                String data = "Request be denied!";
                DataBuffer wrap =
                        response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));

            }
        }


        // 1分钟次数超过2次
        long currentTimeMillis = System.currentTimeMillis();
        if(registerTimesMap.containsKey(clientIp) && registerTimesMap.get(clientIp)>limitCount){
            registerSecondsMap.put(clientIp,currentTimeMillis);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "Request be denied!";
            DataBuffer wrap =
                    response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }else{

            if (registerSecondsMap.containsKey(clientIp)){
                Long aLong = registerSecondsMap.get(clientIp);
                if(currentTimeMillis-aLong>=limitTimes && registerTimesMap.containsKey(clientIp)){
                    registerTimesMap.put(clientIp,0);
                    registerSecondsMap.put(clientIp,currentTimeMillis);
                }else{
                    if(registerTimesMap.containsKey(clientIp)){
                        registerTimesMap.put(clientIp,registerTimesMap.get(clientIp)+1);
                    }else{
                        registerTimesMap.put(clientIp,1);
                    }
                }
            }else{
                registerSecondsMap.put(clientIp,currentTimeMillis);
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
